package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String protocol;
    private String requestURI;
    private String queryString;
    private Map<String,String> parameters  = new HashMap<>();
    private Map<String,String> headers = new HashMap<>();

    public HttpRequest(Socket socket) throws  EmptyRequestException{
        this.socket = socket;
        System.out.println("开始解析请求......");
        parseRequestLine();
        parseHeaders();
        parseContent();
        System.out.println("请求解析完毕！");
    }

    private void parseRequestLine() throws EmptyRequestException{
        System.out.println("开始解析请求行......");
        try {
            String line = readLine();
            if (line.isEmpty()){
                throw new EmptyRequestException();
            }
            String [] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];

            System.out.println("method:"+method+"\nuri:"+uri+"\nprotocol:"+protocol);

            parseUri();
        }catch (EmptyRequestException e){
            throw  e;
        }catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("请求行解析完毕!");
    }

    //进一步解析uri
    private void parseUri(){
        if (uri.indexOf("?")!=-1){
            String [] data = uri.split("\\?");
            requestURI = data[0];
            if (data.length>1){
                queryString = data[1];
                try {
                    queryString = URLDecoder.decode(queryString,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                data = queryString.split("&");
                for (String e : data){
                    String[] arr = e.split("=");
                    if (arr.length>1){
                        parameters.put(arr[0],arr[1]);
                    }else {
                        parameters.put(arr[0],null);
                    }
                }
            }
        }else {
            requestURI = uri;
        }
        System.out.println("requestURI:"+requestURI+"\nqueryString:"+queryString+"\nparameters:"+parameters);
    }

    private void parseHeaders(){
        System.out.println("开始解析消息头......");
            try {
                while (true){
                    String line = readLine();
                    if ("".equals(line)){
                        break;
                    }
                    System.out.println("消息头："+line);
                    String [] data = line.split(":\\s");
                    headers.put(data[0],data[1]);
                }
                System.out.println("headers:"+headers);
            } catch (IOException e) {
                e.printStackTrace();
            }

        System.out.println("消息头解析完毕！");
    }

    private void parseContent(){
        System.out.println("开始解析消息正文");
        System.out.println("消息正文继续完毕！");
    }

    //读取请求的每一行(以回城换行符为每一行的结束标志)
    private String readLine() throws IOException{
            InputStream is = socket.getInputStream();
            int d = 0;
            StringBuilder builder = new StringBuilder();
            while ((d=is.read())!=-1){
                char c = (char)d;
                if (builder.length()!=0&&builder.charAt(builder.length()-1)==13&&c==10){
                    break;
                }
                builder.append(c);
            }
            return builder.toString().trim();
    }

    public String getParameters(String key){
        return parameters.get(key);
    }

    public String getHeaders(String key){
        return headers.get(key);
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }
}
